class Game {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.score = 0;
        this.correctAnswers = 0;
        this.currentProblem = null;
        this.lastProblemTime = 0;
        this.problemInterval = 2000;
        this.effect = null;
        this.effectStartTime = 0;
        this.message = null;
        this.messageStartTime = 0;
        this.effectImage = null;

        // 初始化音效
        this.correctSound = new Audio('res/success.mp3');
        this.wrongSound = new Audio('res/fail.mp3');
        
        // 预加载GIF图片
        this.successGif = new Image();
        this.successGif.src = 'res/success.gif';
        this.failGif = new Image();
        this.failGif.src = 'res/fail.gif';

        // 初始化游戏
        this.init();
    }

    init() {
        // 初始化游戏状态
        this.score = 0;
        this.correctAnswers = 0;
        this.currentProblem = null;
        this.lastProblemTime = 0;
        this.problemInterval = 2000;
        this.effect = null;
        this.effectStartTime = 0;
        this.message = null;
        this.messageStartTime = 0;
        this.effectImage = null;

        // 添加事件监听器
        this.canvas.addEventListener('click', this.handleClick.bind(this));
        this.canvas.addEventListener('touchstart', (e) => {
            e.preventDefault();
            const touch = e.touches[0];
            const simulatedClick = new MouseEvent('click', {
                clientX: touch.clientX,
                clientY: touch.clientY
            });
            this.canvas.dispatchEvent(simulatedClick);
        });

        // 启动游戏循环
        requestAnimationFrame(this.gameLoop.bind(this));
    }

    generateProblem() {
        const num1 = Math.floor(Math.random() * 10);
        const num2 = Math.floor(Math.random() * 10);
        const isAddition = Math.random() > 0.5;
        const operator = isAddition ? '+' : '-';
        const correctAnswer = isAddition ? num1 + num2 : num1 - num2;

        // 生成三个选项，包括正确答案
        let options = [correctAnswer];
        while (options.length < 3) {
            const wrongAnswer = Math.floor(Math.random() * 20) - 5;
            if (!options.includes(wrongAnswer)) {
                options.push(wrongAnswer);
            }
        }
        options = options.sort(() => Math.random() - 0.5);

        return {
            expression: `${num1} ${operator} ${num2} = ?`,
            options,
            correctAnswer,
            y: 0,
            speed: 1
        };
    }

    showEffect(type, message) {
        this.effect = type;
        this.effectStartTime = Date.now();
        this.message = message;
        this.messageStartTime = Date.now();
        
        // 设置对应的GIF图片
        this.effectImage = type === 'fireworks' ? this.successGif : this.failGif;
        
        // 播放音效
        if (type === 'fireworks') {
            this.correctSound.play();
        } else {
            this.wrongSound.play();
        }
    }

    drawFireworks(x, y) {
        const particles = 20;
        const radius = 30;
        for (let i = 0; i < particles; i++) {
            const angle = (Math.PI * 2 * i) / particles;
            const dx = Math.cos(angle) * radius;
            const dy = Math.sin(angle) * radius;
            this.ctx.beginPath();
            this.ctx.moveTo(x, y);
            this.ctx.lineTo(x + dx, y + dy);
            this.ctx.strokeStyle = `hsl(${Math.random() * 360}, 100%, 50%)`;
            this.ctx.stroke();
        }
    }

    drawExplosion(x, y) {
        const particles = 16;
        const radius = 40;
        this.ctx.beginPath();
        this.ctx.arc(x, y, radius, 0, Math.PI * 2);
        this.ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
        this.ctx.fill();

        for (let i = 0; i < particles; i++) {
            const angle = (Math.PI * 2 * i) / particles;
            const dx = Math.cos(angle) * radius;
            const dy = Math.sin(angle) * radius;
            this.ctx.beginPath();
            this.ctx.moveTo(x, y);
            this.ctx.lineTo(x + dx, y + dy);
            this.ctx.strokeStyle = 'red';
            this.ctx.stroke();
        }
    }

    handleClick(event) {
        if (!this.currentProblem || this.effect) return;

        const rect = this.canvas.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;

        const optionHeight = 40;
        const optionY = this.currentProblem.y + 50;

        for (let i = 0; i < 3; i++) {
            const optionX = (this.canvas.width / 3) * i + 20;
            if (x >= optionX && x <= optionX + 100 &&
                y >= optionY && y <= optionY + optionHeight) {
                if (this.currentProblem.options[i] === this.currentProblem.correctAnswer) {
                    this.score += 10;
                    this.correctAnswers++;
                    this.showEffect('fireworks', '小轩轩太棒啦！');
                } else {
                    this.showEffect('explosion', '哎呀，下次努力哦！');
                }
                this.currentProblem = null;
                break;
            }
        }
    }

    gameLoop(timestamp) {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

        if (this.correctAnswers >= 10) {
            this.ctx.fillStyle = 'black';
            this.ctx.font = '30px Arial';
            this.ctx.textAlign = 'center';
            this.ctx.fillText('恭喜你闯关成功！', this.canvas.width / 2, this.canvas.height / 2);
            document.getElementById('score').textContent = `最终得分: ${this.score}`;
            return;
        }

        if (this.effect) {
            const effectDuration = 2000;
            const effectCenter = { x: this.canvas.width / 2, y: this.canvas.height / 2 };
            
            // 显示GIF图片
            if (this.effectImage) {
                const imageSize = 200;
                this.ctx.drawImage(
                    this.effectImage,
                    effectCenter.x - imageSize / 2,
                    effectCenter.y - imageSize / 2,
                    imageSize,
                    imageSize
                );
            }

            // 显示文字提示
            if (this.message) {
                this.ctx.fillStyle = 'black';
                this.ctx.font = '24px Arial';
                this.ctx.textAlign = 'center';
                this.ctx.fillText(this.message, this.canvas.width / 2, this.canvas.height / 2 - 120);
            }

            if (Date.now() - this.effectStartTime >= effectDuration) {
                this.effect = null;
                this.message = null;
                this.effectImage = null;
            }
        } else {
            if (!this.currentProblem && timestamp - this.lastProblemTime >= this.problemInterval) {
                this.currentProblem = this.generateProblem();
                this.lastProblemTime = timestamp;
                this.problemInterval = Math.random() * 3000 + 2000; // 2-5秒
            }

            if (this.currentProblem) {
                this.currentProblem.y += this.currentProblem.speed;

                // 绘制题目
                this.ctx.fillStyle = 'black';
                this.ctx.font = '24px Arial';
                this.ctx.textAlign = 'center';
                this.ctx.fillText(this.currentProblem.expression, 
                    this.canvas.width / 2, this.currentProblem.y);

                // 绘制选项
                this.ctx.font = '20px Arial';
                for (let i = 0; i < 3; i++) {
                    const x = (this.canvas.width / 3) * i + 20;
                    const y = this.currentProblem.y + 50;
                    this.ctx.fillStyle = '#4CAF50';
                    this.ctx.fillRect(x, y, 100, 40);
                    this.ctx.fillStyle = 'white';
                    this.ctx.fillText(this.currentProblem.options[i], x + 50, y + 25);
                }

                if (this.currentProblem.y > this.canvas.height) {
                    this.currentProblem = null;
                    this.showEffect('explosion', '哎呀，下次努力哦！');
                }

                // 绘制选项
                this.ctx.font = '20px Arial';
                for (let i = 0; i < 3; i++) {
                    const x = (this.canvas.width / 3) * i + 20;
                    const y = this.currentProblem.y + 50;
                    this.ctx.fillStyle = '#4CAF50';
                    this.ctx.fillRect(x, y, 100, 40);
                    this.ctx.fillStyle = 'white';
                    this.ctx.fillText(this.currentProblem.options[i], x + 50, y + 25);
                }

                // 绘制选项
                this.ctx.font = '20px Arial';
                for (let i = 0; i < 3; i++) {
                    const x = (this.canvas.width / 3) * i + 20;
                    const y = this.currentProblem.y + 50;
                    this.ctx.fillStyle = '#4CAF50';
                    this.ctx.fillRect(x, y, 100, 40);
                    this.ctx.fillStyle = 'white';
                    this.ctx.fillText(this.currentProblem.options[i], x + 50, y + 25);
                }

                if (this.currentProblem.y > this.canvas.height) {
                    this.currentProblem = null;
                    this.showEffect('explosion');
                }
            }
        }

        document.getElementById('score').textContent = `得分: ${this.score}`;
        requestAnimationFrame(this.gameLoop.bind(this));
    }
}